package com.tutou.ikuser.util;

import com.alibaba.fastjson.JSONObject;
import com.tutou.ikuser.pojo.po.User;
import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

import java.util.Date;

@Slf4j
public class JwtUtil {
    //令牌密钥
    private static String masterKey = "masterKey";

    //令牌有效时间
    private static long expireTime = 1000 * 60 * 60 * 24;

    //生成token
    public static String buildToken(User user) {
        JwtBuilder builder = Jwts.builder();
        String token = builder
                .claim("user", user)
                .setExpiration(new Date(System.currentTimeMillis() + expireTime))
                .signWith(SignatureAlgorithm.HS512, masterKey)
                .compact();
        System.out.println("JWT信息：" + token);
        return token;
    }


    //解析并获取密钥用户名
    public static String getUser(String token) {
        String user;
        try {
            Claims claims = Jwts.parser().setSigningKey(masterKey).parseClaimsJws(token).getBody();
            user = claims.get("user").toString();
        } catch (Exception e) {
            log.error(e.getMessage());

            user = null;
        }
        return user;
    }

    //刷新token有效期
    public static String refreshToken(String token) throws Exception {
        String subject = Jwts.parser().setSigningKey(masterKey).parseClaimsJws(token).getBody().getSubject();
        //验证用户信息
        User user = JSONObject.parseObject(subject, User.class);
        if (ObjectUtils.isEmpty(user)) {
            return "";
        }
        return buildToken(user);
    }

    //jwt有效期清零
    public static void clearToken(String token) {
        Jwts.parser().setSigningKey(masterKey).parseClaimsJws(token).getBody().setExpiration(new Date(0));
    }
}
